package com.lrd.shardingjdbc.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.time.LocalDate;
import java.util.*;

/**
 * 自定义精确分片规则
 *
 * @author LRD
 * @create 2021-03-29 20:12
 */
public class BirthdayAlgorithm implements PreciseShardingAlgorithm<LocalDate> {

    List<LocalDate> dateList = new ArrayList();

    {

        LocalDate date1 = LocalDate.of(2021, 1, 1);
        LocalDate date2 = LocalDate.of(2022, 1, 1);

        dateList.add(date1);
        dateList.add(date2);
    }

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<LocalDate> preciseShardingValue) {
        //获取属性数据的真实值
        LocalDate date = preciseShardingValue.getValue();
        //获取数据源的名称信息列表
        Iterator<String> iterator = collection.iterator();
        String target = null;
        for (LocalDate s : dateList) {
            target = iterator.next();
            //如果数据晚于指定的日期直接返回
            if (date.isBefore(s)) {
                break;
            }
        }
        return target;
    }
}
